package com.lhy.utilsdemo.aboutFile.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Liu Hangyu
 * @date 2022/3/10 10:27
 */
@Service
public class FileServiceImpl {


    @Value("${baesFilePath}")
    private String baesFilePath;


    public Map upLoadFile(MultipartFile file, String paramFilePath) {
        Map resultMap = new HashMap();
        java.util.Date date = new java.util.Date();
        //拼接业务文件路径
        String path = paramFilePath+"/"+ new SimpleDateFormat("yyyy-MM-dd/HH-mm-ssSSSS").format(date) + "/";
        System.out.println(path);
        String fileRoute = baesFilePath + path;
        File targetFile = new File(fileRoute);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try (FileOutputStream out = new FileOutputStream(fileRoute + file.getOriginalFilename());) {
            out.write(file.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件上传失败!");
            resultMap.put("type", "fail");
            resultMap.put("fileName", file.getOriginalFilename());
            resultMap.put("path", path);
            return resultMap;
        }
        System.out.println("文件上传成功!");
        resultMap.put("type", "success");
        resultMap.put("fileName", file.getOriginalFilename());
        resultMap.put("path", path);
        return resultMap;
    }
}
